#coding=utf-8
'''this file is a client of seyren'''
import urllib2,urllib
import json,random,string,time

logger = open('log','w')
#check_url = 'http://9.186.89.218:8081/api/checks/'
check_url = 'http://9.186.107.15:8081/api/checks/'
#check_url = 'http://9.181.61.63:8080/seyren-web/api/checks/'
header = {}
header['Content-Type']='application/json;charset=UTF-8'

def getMetrics():
	line = open('index.json').readlines()[0]
	l =  json.loads(line)
	print 'total Metric:',len(l)
	metrics = []
	for e in l:
		#if e.startswith('localhost') and '-' not in e:
		#	metrics.append(e)
		metrics.append(e)
	return metrics

operators = ['>','<','>=','<=']

def constructCheck(metrics,operators,num_target=None):
	name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
	desc = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7))
	if num_target == None:
		num_target = random.randint(0,len(metrics)-1)
	num_op = random.randint(0,len(operators) - 1)
	threshold = [random.randint(0,100),random.randint(0,100)]
	target = metrics[num_target].decode('utf-8')
	check = {}
	check['name']= name
	#check['name']= '38FUYTZPRP'
	check['description']= desc
	check['target']= target
	check['enabled']=True
	check['live']=False
	check['allowNoData']=False
	type = 'normal'

	if type == 'huchi':
		check['warn_str']= target + ' ' + operators[num_op] + ' ' + str(threshold[0])
		check['error_str']= target + ' ' + operators[3-num_op] + ' ' + str(threshold[0])
	elif type == 'normal':
		check['warn_str']= target + ' ' + operators[num_op] + ' ' + str(threshold[0])
		check['error_str']= target + ' ' + operators[num_op] + ' ' + str(threshold[1])
		
	check['type']='1'
	return check

def normal_check(target='bigant-test-003.cpu-0.cpu-idle'):
	name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
	desc = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7))
	check = {}
	check['name']= name
	#check['name']= '38FUYTZPRP'
	check['description']= desc
	check['target']= target + ',bigant-test-004.cpu-0.cpu-idle'
	check['enabled']=True
	check['live']= False
	check['allowNoData']=False
	check['warn_str']= target + ' > 90'
	check['error_str']= target + ' > 95 '
	check['type']='1'
	return check

def sql_check():
	check = {}
	name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
	desc = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7))
	check['name']=name
	check['description'] = desc
	check['warn_str']=''
	check['error_str']=''
	check['enabled']=True
	check['live']=False
	check['allowNoData']= False
	check['type'] = '2'
	return check

def constructsqlcheck(metrics,operators,num_target=None):
	check = sql_check()
	num_op = random.randint(0,len(operators) - 1)
        threshold = [random.randint(0,100),random.randint(0,100)]
	if num_target == None:
		num_target = random.randint(0,len(metrics)-1)
        target = metrics[num_target].decode('utf-8')
        check['warn_str'] = 'select "bigant-test-003.cpu-0.cpu-idle" where "bigant-test-003.cpu-0.cpu-idle" > 90'
        #check['error_str'] = 'select "bigant-test-003.cpu-0.cpu-idle" where "bigant-test-003.cpu-0.cpu-idle" > 95'
	return check

def createCheck():
	metrics = getMetrics()
	#print metrics
	print len(metrics)
	#data =  urllib.urlencode(check)
	total = 1
	while True:
		#if total % 5 == 0 : time.sleep(45)
		#if total >= len(metrics): break
		if total >= 2: break
		#check = constructCheck(metrics,operators,num_target=total)
		##random check
		#check = constructCheck(metrics,operators)
		## reasonable check
		check = normal_check()
		## sqlcheck
		#check = constructsqlcheck(metrics,operators)
		data = json.dumps(check)
		print data
		req = urllib2.Request(check_url,data,header)
		localtime = time.asctime(time.localtime(time.time()))
		logger.write(localtime+' '+data+'\n')
		
		try:
			#res = urllib2.urlopen(req,timeout=30)
			res = urllib2.urlopen(req)
			print res.getcode(),res.info().getheader('Location')
		except urllib2.HTTPError,e:
			print e.code,e.read()
			logger.write(str(e.code)+' '+ str(e.read()) +' ' +'\n')
			break
		except urllib2.URLError,e:
			print e.args,e.reason
			logger.write(str(e.args)+' ' + str(e.reason) + '\n')
			break
		
		total += 1

def getCheck():
	try:
		req = urllib2.Request(check_url,headers=header)
		res = urllib2.urlopen(req)
		checkIds = []
		res = json.loads(res.read())
		checks = res['values']
		for check in checks:
			checkIds.append(check['id'])
		return checkIds
	except urllib2.HTTPError,e:
		print e.code,e.read()
	except urllib2.URLError,e:
		print e.args,e.reason
	return []

def getAlert(checkIds):
	num = random.randint(0,len(checkIds)-1)
	checkId = checkIds[num]
	alert_url = check_url + str(checkId) + '/alerts' 
	print alert_url
	logger.write(alert_url + '\n')
	try:
		req = urllib2.Request(alert_url,headers=header)
		res = urllib2.urlopen(req)
		res = json.loads(res.read())
	except urllib2.HTTPError,e:
		print e.code,e.read()
		logger.write(str(e.code)+' '+ str(e.read()) +' ' +'\n')
	except urllib2.URLError,e:
		print e.args,e.reason
		logger.write(str(e.args)+' ' + str(e.reason) + '\n')
	
	
def getAlerts():
	checkIds = getCheck()
	while True:
		getAlert(checkIds)



if __name__ == '__main__':
	createCheck()
	#getCheck()
	#getAlerts()
	#print '\n'.join(getMetrics())
	logger.flush()
	logger.close()
